package com.moonshineproject.plugin.actionscript.as3parser.listener
{
	import com.moonshineproject.GlobalEventDispatcher;
	import com.moonshineproject.events.SaveFileEvent;
	import com.moonshineproject.plugin.actionscript.as3parser.MetadataManager;
	import com.moonshineproject.plugin.actionscript.as3parser.SourceFileParser;
	import com.moonshineproject.plugin.actionscript.as3parser.swcparser.SWCManager;
	import com.moonshineproject.plugin.actionscript.as3parser.vo.PackageVO;
	import com.moonshineproject.plugin.actionscript.as3project.vo.AS3ProjectVO;
	
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.utils.getTimer;
	
	public class ParserController
	{
		public var metadata:MetadataManager;
		
		protected var project:AS3ProjectVO;
		protected var dispatcher:GlobalEventDispatcher; 
		
		
		public function ParserController(p:AS3ProjectVO)
		{
			dispatcher = GlobalEventDispatcher.getInstance();
			this.project = p;
			
			metadata = new MetadataManager(p.classpaths);
			
			projectOpened();
			
			addListeners();
		}
		
		public function addListeners():void
		{
			dispatcher.addEventListener(SaveFileEvent.FILE_SAVED, handleFileSaved);
		}
		
		public function removeListeners():void
		{
			dispatcher.removeEventListener(SaveFileEvent.FILE_SAVED, handleFileSaved);
		}
		
		protected function projectOpened():void
		{	
			// TODO: Parse all SDK swcs auto-added by the compiler (Flex & Playerglobals)
			var swcManager:SWCManager = new SWCManager();
			
			var compilerSWCs:Vector.<File> = swcManager.getCompilerSWCS(project);
			for each (var lib:File in compilerSWCs)
			{
				if (project.externalLibraries.indexOf(lib) == -1)
				{
					var pkg:PackageVO = swcManager.getContents(lib);
					metadata.globalPackageCache.merge(pkg);
				}
			}
			
			// Parse all external libraries linked in
			for each (var file:File in project.externalLibraries)
			{
				if (!file.exists || file.isDirectory) continue;
				pkg = swcManager.getContents(file);
				metadata.globalPackageCache.merge(pkg);
			}
			
			var now:int = flash.utils.getTimer();
			
			// Parse all source files in project
			var fileParser:SourceFileParser = new SourceFileParser(metadata, project.classpaths);
			for each (var dir:File in project.classpaths)
			{
				fileParser.parseDir(dir, dir, false);
			}
			trace("Up front source code definition parsing took: " + (flash.utils.getTimer()-now) + " ms");
		}
		
		protected function handleFileSaved(event:SaveFileEvent):void
		{
			if (!project.projectFolder.containsFile(event.file)) return
			
			var fileParser:SourceFileParser = new SourceFileParser(metadata, project.classpaths);
			fileParser.parseFile(event.file);
		}
		
		protected function handleFileAdded(event:Event):void
		{
			
		}
		
		protected function handleFileRemoved(event:Event):void
		{
			
		}
		
		protected function handleFileMoved(event:Event):void
		{
			
		}

	}
}